<?php

  function code2openid() {
    $appid = 'wxe20d16baf3de2c93';
    $sessionKey = '58172eee2a9ef3cbeccab2def3d6f1ff';
    $code = $_POST['code'];
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$sessionKey}&js_code={$code}&grant_type=authorization_code";
    $resp = file_get_contents($url);
    $robot = json_decode($resp);
    return $robot -> openid;
  }


  function login() {
    $openid = $_POST['openid'];
    $sql = "SELECT * FROM `user` where `openid`='$openid'";
    $query = mysql_query($sql);
    while ($rs = mysql_fetch_array($query)) $user = array(
      'id' => $rs['id'],
      'username' => $rs['username'],
      'id_card' => $rs['id_card'],
      'phone' => $rs['phone'],
      'gender' => $rs['gender'],
      'DP' => $rs['DP'],
      'job' => $rs['job'],
      'post' => $rs['post'],
      'CR' => $rs['CR'],
      'RS' => $rs['RS'],
      'PS' => $rs['PS'],
      'NT' => $rs['NT'],
      'EDU' => $rs['EDU'],
      'ED' => $rs['ED'],
      'date' => $rs['date'],
      'validity' => $rs['validity'],
      'level' => $rs['level'],
      'note' => $rs['note'],
    );
    print_r(json_encode($user));
  }
  

  function register() {
    $openid = $_POST['openid'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $nick = $_POST['nick'];
    $avatar = $_POST['avatar'];
    $city = $_POST['city'];
    $gender = $_POST['gender'];
    $language = $_POST['language'];

    $sql = "INSERT INTO `user` (`name`, `openid`, `phone`, `nick`, `avatar`, `gender`, `city`, `language`) VALUES ('{$name}', '{$openid}', '{$phone}', '{$nick}', '{$avatar}', '{$gender}', '{$city}', '{$language}');";
    $query = mysql_query($sql);
    $sql = "SELECT * FROM `user` where `openid` = '$openid'";
    $query = mysql_query($sql);
    while ($rs = mysql_fetch_array($query)) $user = array(
      'id' => $rs['id'],
      'name' => $rs['name'],
      'nick' => $rs['nick'],
      'gender' => $rs['gender'],
      'phone' => $rs['phone'],
      'contact' => $rs['contact'],
      'validity' => $rs['validity'],
      'last_login' => $rs['last_login'],
      'date' => $rs['date'],
      'city' => $rs['city'],
      'language' => $rs['language'],
      'introduction' => $rs['introduction'],
      'avatar' => $rs['avatar'],
    );
    print_r(json_encode($sql));  
    mysql_close($link);
  }


  function updateUser() {
    $id = $_POST['id'];
    $avatar = $_POST['avatar'];
    $last_login = $_POST['last_login'];
    if ($avatar == 'null') $sql = "UPDATE `user` set `last_login` = '$last_login' where `id`='$id'";
    else $sql = "UPDATE `user` set `last_login` = '$last_login', `avatar` = '$avatar' where `id`='$id'";
    $query = mysql_query($sql);
    print_r(json_encode('UserInfo has updated.'));
  }
  
?>